require 'aws'
require File.dirname(__FILE__) + '/../common/rightscale-api'
begin
  require 'xmlsimple' unless defined? XmlSimple
rescue Exception => e
  require 'xml-simple' unless defined? XmlSimple
end

class Volume < RightScaleAPI

  def initialize(api = RightAPI.new)
    super(api)
    @amazon_api = AWS::EC2::Base.new(:access_key_id => AWS_ACCESS_KEY_ID, :secret_access_key => AWS_SECRET_ACCESS_KEY)
  end

  def create_from_snapshot(availability_zone, size, snapshot_id, nickname, description, timeout)
    result = @amazon_api.create_volume(:availability_zone => availability_zone, :size => size, :snapshot_id => snapshot_id)
    amazon_volume_id = result["volumeId"]
    volume_href = wait_until_volume_is_available(amazon_volume_id, timeout)
    volume_id = volume_href.split("/").last
    update volume_id, nickname, description
    puts "created volume, amazonid = #{amazon_volume_id}, #{volume_href}"
    volume_id
  end

  def wait_until_volume_is_available(volume_id, timeout)
    elapsed = 0

    until elapsed >= timeout
      elapsed += 5
      xml = @api.send("ec2_ebs_volumes")
      response = XmlSimple.xml_in(xml, {'forcearray' => ['item', 'member'], 'suppressempty' => nil, 'keeproot' => false})
      volume_node = response["ec2-ebs-volume"].select { |k| k["aws-id"] == volume_id }
      if (volume_node.count > 0)
        puts "status = #{volume_node[0]["aws-status"]}"
        puts "href = #{volume_node[0]["href"]}"
        return volume_node[0]["href"] if (volume_node[0]["aws-status"] == "available")
      end
      puts "sleeping for 5 seconds, elapsed: #{elapsed}"
      sleep 5
    end
    raise "time out error, volume #{volume_id} was not available on time"
  end

  def update(volume_id, nickname, description)
    params = {
        'ec2_ebs_volume[nickname]'    => nickname,
        'ec2_ebs_volume[description]' => description,
    }
    @api.send("ec2_ebs_volumes/#{volume_id}", "put", params)
  end

  def attach_to_server(volume_id, server_id, device, mount_on_boot = true)
    params = {
        'component_ec2_ebs_volume[ec2_ebs_volume_href]' => "#{HREF_URL}/ec2_ebs_volumes/#{volume_id}",
        'component_ec2_ebs_volume[component_href]' => "#{HREF_URL}/servers/#{server_id}",
        'component_ec2_ebs_volume[device]' => device,
        'component_ec2_ebs_volume[mount]' => "boot",
    }

    @api.send("component_ec2_ebs_volumes", "post", params)
    puts "attaching volume: #{@api.headers}"

    @api.send("servers/#{server_id}/current/reboot", "post")
    puts "reboot server: #{@api.headers}"
  end

end